package org.example;

import cn.hutool.json.JSONUtil;
import org.example.util.Constant;
import org.example.util.JwtToken;
import org.example.util.Result;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String s = request.getPath().toString();
        if (s.contains("/login")){
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst(Constant.TOKEN_NAME);
        try {
            Map<String, Object> map = JwtToken.resolveJwt(token);
        }catch (Exception e){
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", "application.yml/json");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String str = JSONUtil.toJsonStr(Result.ERROR("token过期或者不存在，请重新登陆"));
            DataBuffer wrap = response.bufferFactory().wrap(str.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}